/**
 *
 * Copyright Pact Lab of H.I.T.
 *
 * Designed and Implemented by Grid Researching Group, 
 * Pact Lab, Harbin
 * 
 * This Project is part of the national 973 Project:
 * Internet Based Virtual Computing Environment
 *
 * http://pact518.hit.edu.cn
 * 
 * Author:       Meteor <meteorlxk@gmail.com> 
 * Copyright:    pact518 
 * Version:      1.0
 * Created:      2008-11-18 
 * LastModified: 2008-11-18
 */

package edu.hit.pact.pgse.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import org.apache.commons.logging.Log;

public abstract class AbstractThread extends Thread{
	private Log logger;
	private int interval; //seconds
	private boolean isDeadLoop;
	
	public AbstractThread(Log logger){
		this(logger, 0, true);
	}	
	
	public AbstractThread(Log logger, int interval){
		this(logger, interval, true);
	}
	
	public AbstractThread(Log logger, int interval, boolean isDeadLoop){

//		try {
//			PrintWriter runTracker = new PrintWriter(new FileOutputStream(this.threadName, true), true);
//			runTracker.close();
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		this.logger = logger;
		this.interval = interval;
		this.isDeadLoop = isDeadLoop;
	}
	
	public AbstractThread(Log logger, int interval, boolean isDeadLoop,String threadName){
		super(threadName);
		this.logger = logger;
		this.interval = interval;
		this.isDeadLoop = isDeadLoop;
	}
	
	
	public int getInterval() {
		return interval;
	}

	public void setInterval(int interval) {
		this.interval = interval;
	}

	public boolean isDeadLoop() {
		return isDeadLoop;
	}

	public void setDeadLoop(boolean isDeadLoop) {
		this.isDeadLoop = isDeadLoop;
		
	}

	public void run(){
//		logger.info(logger.toString()+" I am running.");
		do{
			/*
			 * in case a RuntimeException be thrown out
			 * and end the main loop, we catch it
			 */
			try {
				mainRun();
			} catch (RuntimeException e) {
				logger.error("meets runtime exceptions", e);
			}
					
			if (interval > 0) {
				try {
					sleep(interval * 1000);
				} catch (InterruptedException e) {
					logger.error("meets interrupted exceptions", e);
				}
			}
			
			if (!isDeadLoop) {
				logger.info("Be dying right now.");
//				File file = new File(threadName);
//				logger.error("Thread " + threadName+ " file has delete "+ file.delete());
				return;
			}
		}while(isDeadLoop);
	}
	
	// if something wrong return false
	abstract public void mainRun();
}
